<template>
  <view class="timer-container">
    <!-- 运动项目名称区域 -->
    <view class="timer-top">
      <view class="timer-title">{{sportName}}</view>
    </view>
    <!-- 时间区域 -->
    <view class="timer-time">
      <view class="time">{{time}}</view>
    </view>

    <!-- 运动计时记录区域 -->
    <scroll-view class="timer-record-scroll" scroll-y>
      <view class="timer-prompt" v-if="todayRecord.record && todayRecord.record.length<=0">今天还没有运动记录哦~</view>
      <uni-swipe-action>
        <view class="timer-record" v-for="(item, i) in todayRecord.record" :key="i">
          <uni-swipe-action-item :right-options="options" @click="deleteRecord(i)">
            <view class="record-item">
              <view class="record-number">{{item.number}}</view>
              <view class="record-type">{{item.type}}</view>
              <view class="record-project">{{item.project}}</view>
              <view class="record-time">{{item.time}}</view>
            </view>
          </uni-swipe-action-item>
        </view>
      </uni-swipe-action>
    </scroll-view>

    <!-- 按钮区域 -->
    <view class="timer-icons">
      <view :class="['btn', musicRun === 1 ? 'btn-rec-music' : 'btn-music']" hover-class="btn-hover"
        hover-stay-time="50" @click="changeMusicState"></view>
      <view :class="['btn', 'btn-rec', state === 1 ? 'btn-rec-pause' : state === 2 ? 'btn-rec-play' : 'btn-rec-normal']"
        hover-class="btn-hover" hover-stay-time="50" @click="startTimer"></view>
      <view :class="['btn', stop === 1 ? 'btn-rec-stop' : 'btn-stop']" hover-class="btn-hover" hover-stay-time="50"
        @click="resettingTimer"></view>
    </view>

  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
  } from 'vuex'
  export default {
    data() {
      return {
        // 当前日期
        currentDate: '',
        // 今天运动记录
        todayRecord: {},
        // 运动项目标题
        sportTitle: '',
        // 运动项目名称
        sportName: '',
        // 计时器参数
        time: '00:00:00',
        startTime: 0,
        endTime: 0,
        totalTime: 0,
        timer: null,
        isRunning: false,
        pauseTime: 0,
        pauseTimer: null,
        // 按钮状态
        state: 0,
        stop: 0,
        musicRun: 0,
        // 右滑删除控件
        options: [{
          text: '删除',
          style: {
            backgroundColor: 'orangered'
          },
        }]
      };
    },
    computed: {
      ...mapState('m_music', ['audioCtx', 'audioState', 'playIndex']),
      ...mapState('m_user', ['recordList']),
    },
    onLoad(options) {
      const title = decodeURIComponent(options.title);
      const name = decodeURIComponent(options.name);
      this.sportTitle = title
      this.sportName = name

      this.getNowDate()
      this.getTodayRecord()
      // 音乐按钮
      if (this.audioState === 'running') {
        this.musicRun = 1
      }
    },
    methods: {
      ...mapMutations('m_music', ['setState', 'setMusic']),
      ...mapMutations('m_user', ['updateUserRecordList']),

      // 获取当前日期
      getNowDate() {
        // 获取当前日期
        const date = new Date();
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        // 添加0前缀
        if (month < 10) {
          month = '0' + month;
        }
        if (day < 10) {
          day = '0' + day;
        }
        this.currentDate = `${year}-${month}-${day}`;
        console.log(this.currentDate);
      },
      // 获取今天运动记录
      getTodayRecord() {
        if (this.recordList.length !== 0) {
          const currentRecord = this.recordList.find(record => record.date === this.currentDate);
          if (currentRecord) {
            const todayRecord = {
              date: this.currentDate,
              record: currentRecord.record
            }
            this.todayRecord = todayRecord
            return
          }
        }
        const todayRecord = {
          date: this.currentDate,
          record: []
        }
        this.todayRecord = todayRecord
        console.log(this.todayRecord.record)
      },

      // 开始计计时器
      startTimer() {
        if (this.state === 0 && this.time == '00:00:00') {
          this.state = 1
          clearInterval(this.timer)
          clearInterval(this.pauseTimer)
          console.log(this.time)
          this.time = '00:00:00'
          this.startTime = new Date().getTime()
          this.isRunning = true
          this.pauseTime = 0
          this.timer = setInterval(() => {
            const currentTime = new Date().getTime();
            const timeDiff = currentTime - this.startTime - this.pauseTime;
            const hours = Math.floor((timeDiff / (1000 * 60 * 60)) % 24).toString().padStart(2, '0');
            const minutes = Math.floor((timeDiff / (1000 * 60)) % 60).toString().padStart(2, '0');
            const seconds = Math.floor((timeDiff / 1000) % 60).toString().padStart(2, '0');
            this.time = `${hours}:${minutes}:${seconds}`
          }, 1000)
        } else if (this.state === 1 && this.time != '00:00:00') {
          this.state = 2
          clearInterval(this.timer)
          clearInterval(this.pauseTimer)
          console.log(this.time)
          this.isRunning = false
          this.pauseTime = new Date().getTime() - this.startTime
        } else if (this.state === 2 && this.time != '00:00:00') {
          this.state = 1
          clearInterval(this.timer)
          clearInterval(this.pauseTimer)
          this.isRunning = true
          this.startTime = new Date().getTime() - this.pauseTime
          this.pauseTime = 0
          this.timer = setInterval(() => {
            const currentTime = new Date().getTime();
            const timeDiff = currentTime - this.startTime - this.pauseTime;
            const hours = Math.floor((timeDiff / (1000 * 60 * 60)) % 24).toString().padStart(2, '0');
            const minutes = Math.floor((timeDiff / (1000 * 60)) % 60).toString().padStart(2, '0');
            const seconds = Math.floor((timeDiff / 1000) % 60).toString().padStart(2, '0');
            this.time = `${hours}:${minutes}:${seconds}`
          }, 1000)
        }
      },
      // 重置计时器
      resettingTimer() {
        if (this.stop == 0) {
          this.stop = 1
          setTimeout(() => {
            this.stop = 0
          }, 300);
        }
        this.state = 0
        clearInterval(this.timer)
        clearInterval(this.pauseTimer)

        // 调用 更新今天的运动记录 方法
        this.updateTodayRecord()
        // 调用 将今天的运动记录更新到所有运动记录中 方法
        this.updateRecordList()

        this.time = '00:00:00'
        this.startTime = 0
        this.endTime = 0
        this.totalTime = 0
        this.isRunning = false
        this.pauseTime = 0
      },

      // 更新今天的运动记录
      updateTodayRecord() {
        const record = {
          number: this.todayRecord.record.length + 1,
          type: this.sportTitle,
          project: this.sportName,
          time: this.time
        }
        this.todayRecord.record.unshift(record)
      },
      // 将今天的运动记录更新到所有运动记录中
      async updateRecordList() {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          record: this.todayRecord
        }
        const {
          data: res
        } = await uni.$http.post('/api/update/record', query)
        if (res.meta.status !== 200) return uni.$showMsg('新增运动记录失败')
        this.updateUserRecordList(res.message)
      },
      // 右滑删除运动记录
      async deleteRecord(e) {
        this.todayRecord.record.splice(e, 1); // 删除 index 索引对应的记录
        this.updateRecordList()
      },

      // 更新背景音乐状态
      changeMusicState() {
        if (this.audioCtx.play === undefined) {
          return uni.$showMsg('先去选择音乐播放吧~')
        } else {
          if (this.musicRun === 1 && this.audioState === 'running') {
            this.musicRun = 0
            this.audioCtx.pause()
            this.setState('paused')
          } else if (this.musicRun === 0 && this.audioState === 'paused') {
            this.musicRun = 1
            this.setMusic(this.playIndex)
            this.audioCtx.play()
            this.setState('running')
          }
        }
      },
    }
  }
</script>

<style lang="scss">
  .timer-container {
    height: calc(100vh - 280rpx);
    display: flex;
    flex-direction: column;
    // border: 1px solid black;

    .timer-top {
      // height: 100rpx;
      width: 100%;
      padding: 13% 25% 0 25%;

      .timer-title {
        height: 70rpx;
        width: 50%;
        background-color: #fba007;
        border-radius: 15rpx;
        letter-spacing: 4rpx;
        color: white;
        font-weight: bold;
        line-height: 70rpx;
        text-align: center;
        // box-shadow: 0px 2px 4px 0.1px #c9c9ca;
        box-shadow: 0px 1px 2px 0.1px #ddd;
      }
    }


    .timer-time {
      // height: 200rpx;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 80rpx 0 60rpx 0;

      // margin-top: 90rpx;
      .time {
        font-size: 55pt;
      }
    }

    .timer-icons {
      height: 200rpx;
      display: flex;
      justify-content: space-around;
      align-items: center;
      position: fixed;
      bottom: 80rpx;
      left: 40rpx;
      right: 40rpx;
      // border: 1px solid red;

      .btn {
        background-color: #eee;
        color: #aaa;
        width: 18vw;
        height: 18vw;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 10vw;
        font-family: Arial;
        transition: all .2s;
        opacity: .95;
      }

      .btn-hover {
        transform: scale(.9);
        opacity: 1;
      }

      .btn-rec {
        padding: 5vw;
        // background-color:#ff1a2b;
        background-color: #fba007;
        color: #eee;
      }

      .btn-music::before {
        content: '\266B';
      }

      .btn-stop::before {
        font-family: 'iconfont';
        content: '\e6d8';
      }

      .btn-rec-music::before {
        content: '\266B';
        color: #fba007;
        animation: rotate 10s linear infinite;
      }

      @keyframes rotate {
        0% {
          transform: rotate(0deg);
        }

        100% {
          transform: rotate(360deg);
        }
      }

      .btn-rec-stop::before {
        font-family: 'iconfont';
        content: '\e6d8';
        color: #fba007;
      }

      .btn-rec-play::before {
        font-family: 'iconfont';
        content: '\e74f';
        font-size: 14vw;
        text-indent: 2vw;
      }

      .btn-rec-normal::before {
        font-family: 'iconfont';
        content: '\e714';
        font-size: 14vw;
      }

      .btn-rec-pause::before {
        font-family: 'iconfont';
        content: '\e667';
        font-size: 12vw;
      }
    }

    .timer-record-scroll {
      // height: 360rpx;
      flex: 1;
      // border: 1px solid red;
      overflow: hidden;
      margin-bottom: 80rpx;

      .timer-prompt {
        height: 90rpx;
        line-height: 90rpx;
        padding: 100rpx 0;
        color: #ccc;
        text-align: center;
        margin: auto;
        // border: 1px solid red;
      }

      .timer-record {
        .record-item {
          height: 90rpx;
          display: flex;
          // justify-content: space-between;
          align-items: center;
          text-align: center;
          margin: 10rpx 30rpx;
          padding: 0 20rpx;
          background-color: white;
          border-radius: 15rpx;
          border: 1px solid #eee;

          .record-number {
            width: 50rpx;
            // border: 1px solid red;
          }

          .record-type {
            width: 150rpx;
            // border: 1px solid red;
          }

          .record-project {
            flex: 1;
            // border: 1px solid red;
          }

          .record-time {
            width: 150rpx;
            // border: 1px solid red;
          }
        }
      }
    }
  }




  @font-face {
    font-family: 'iconfont';
    src: url('data:font/ttf;charset=utf-8;base64,AAEAAAANAIAAAwBQRkZUTZPbJ+MAAAc8AAAAHEdERUYAKQANAAAHHAAAAB5PUy8yPJxKHgAAAVgAAABgY21hcM7z0LkAAAHQAAABWmdhc3D//wADAAAHFAAAAAhnbHlmfnOjzAAAAzwAAAEIaGVhZCFVRNcAAADcAAAANmhoZWEHQAOFAAABFAAAACRobXR4DgABXgAAAbgAAAAWbG9jYQCUAMIAAAMsAAAAEG1heHABEwAsAAABOAAAACBuYW1lXoIBAgAABEQAAAKCcG9zdKn2KT4AAAbIAAAASwABAAAAAQAA8zKzo18PPPUACwQAAAAAAN8bgG0AAAAA3xuAbQ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AAAAEAAAAA1aQnCAAAAADfG4BtAAAAAN8bgG0=') format('truetype');
    font-weight: normal;
    font-style: normal;
    font-display: swap;
  }
</style>